import zipfile
import rarfile
from pathlib import Path
import os
import re

def unrar_file(filename):
    new_zip_dir = filename.rsplit('\\',1)[0] + '/data'
    if not os.path.isdir(new_zip_dir):
        os.makedirs(new_zip_dir)

    rar = rarfile.RarFile(filename, mode='r')
    rar.extractall(new_zip_dir)
    rar.close()

def unzip(path,zfile):
    file_path=path+os.sep+zfile
    print("file_path",file_path)
    desdir=path+os.sep+zfile[:zfile.index('.zip')]
    print("desdir",desdir)
    srcfile=zipfile.ZipFile(file_path)
    print("srcfile",srcfile)
    for filename in srcfile.namelist():
        srcfile.extract(filename,desdir)
        if filename.endswith('.zip'):
            # if zipfile.is_zipfile(filename):
            path=desdir
            zfile=filename
            unzip(path,zfile)


if __name__ == '__main__':
    dir_path = r"D:\Python\python-web-crawler-master\python-web-crawler\saved files"
    file_name_list = os.listdir(dir_path)
    for file_name in file_name_list:
        print(file_name)
        file_name_path = os.path.join(dir_path, file_name)
        if os.path.isfile(file_name_path):
            #print("准备解压",file_name_path)
            if file_name.endswith('.zip'):
                unzip(file_name_path,file_name)
                print(file_name_path,"解压成功")
            elif file_name.endswith('.rar'):
                unrar_file(file_name_path)
                print(file_name_path, "解压成功")

        else:
            print("解压失败",file_name_path)